import {
  useFormContext,
  useWatch,
  type FieldValues,
  type Path,
} from "react-hook-form";
import type { IFieldConfig } from "../types";

const useFormFieldDisabled = <TFormValues extends FieldValues = FieldValues>(
  disabled: IFieldConfig<TFormValues>["disabled"]
) => {
  const form = useFormContext<TFormValues>();
  const dependsOn =
    disabled && typeof disabled === "object" ? disabled?.dependsOn || [] : [];

  const dependsOnValue = useWatch({
    control: form.control,
    name: dependsOn as Path<TFormValues>[],
  });

  if (typeof disabled === "boolean") {
    return disabled;
  }

  if (disabled && typeof disabled === "object") {
    return disabled.handler(dependsOnValue as unknown as TFormValues);
  }
  return false;
};

export default useFormFieldDisabled;
